//
//  UIViewController+extension.swift
//  iUtil
//
//  Created by wendachuan on 19/3/22.
//  Copyright © 2019年 wendachuan. All rights reserved.
//

import UIKit

public extension UIViewController {

    func pushViewController(_ viewController: UIViewController) {
        if let navi = self.navigationController {
            navi.pushViewController(viewController, animated: true)
        } else {
            if let navi = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
                navi.pushViewController(viewController, animated: true)
            }
        }
    }

    func pop() {
        if let navi = self.navigationController {
            navi.popViewController(animated: true)
        } else {
            if let navi = UIApplication.shared.keyWindow?.rootViewController as? UINavigationController {
                navi.popViewController(animated: true)
            }
        }
    }
    
    class func setupClass() {
        replaceMethod(#selector(viewDidLoad), withMethod: #selector(mob_viewDidLoad))
    }

    fileprivate class func replaceMethod(_ originalSelector: Selector, withMethod swizzledSelector: Selector) {
        if let originalMethod = class_getInstanceMethod(self, originalSelector) {
            if let swizzledMethod = class_getInstanceMethod(self, swizzledSelector) {
                let didAddMethod = class_addMethod(self, originalSelector, method_getImplementation(swizzledMethod), method_getTypeEncoding(swizzledMethod))
                if didAddMethod {
                    class_replaceMethod(self, swizzledSelector, method_getImplementation(originalMethod), method_getTypeEncoding(originalMethod))
                } else {
                    method_exchangeImplementations(originalMethod, swizzledMethod)
                }
            }
        }
    }

    @objc func mob_viewDidLoad() {
        self.mob_viewDidLoad()
        let backButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItem.Style.plain, target: nil, action: nil)
        self.navigationItem.backBarButtonItem = backButtonItem
    }

//    func mob_viewDidAppear() {
//        self.mob_viewDidAppear()
//    }
//
//    func mob_viewDidLayoutSubviews() {
//        self.mob_viewDidLayoutSubviews()
//    }
}

extension UIApplication {
    private static let runOnce: Void = {
        UIViewController.setupClass()
    }()
    
    override open var next: UIResponder? {
        // Called before applicationDidFinishLaunching
        UIApplication.runOnce
        return super.next
    }
}
